package com.blockmeta.bbs.businesslibrary.net.callback;

import com.blankj.utilcode.util.LogUtils;

import com.blankj.utilcode.util.LogUtils;
import com.blockmeta.bbs.baselibrary.base.app.BaseApp;
import com.blockmeta.bbs.businesslibrary.net.ACache;
import com.blockmeta.bbs.businesslibrary.util.ReportIssue;
import com.google.gson.JsonParseException;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public abstract class CommonWebCallback<T> implements Callback<T> {
    private String m_strKey;

    public ACache aCache;

    public CommonWebCallback(String logKey) {
        m_strKey = logKey;
        aCache = ACache.get(BaseApp.getApp());
    }

    protected T preSuccess(T result) {
        return result;
    }

    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        int code = response.code();

        try {
            if (code == 200) {

                T result = response.body();
                LogUtils.d("REST-API", "[onSuccess] [" + m_strKey + "] response = " + result);

                result = preSuccess(result);

                if (result != null) {

                    aCache.put(call.request().url().toString(), result.toString());

                    onSuccess(result);
                }


            } else {
                String message = response.message();
                LogUtils.d("REST-API", "[onError] [" + m_strKey + "] error = " + message);
                message = aCache.getAsString(call.request().url().toString());//todo 还不能反序列化成对象
                if (message == null) {
                    message = response.message();
                }

                onError(new Throwable(message));
            }
        } catch (Exception e) {
            if(e instanceof JsonParseException){
                ReportIssue.recordHttpParseErrorIssue(call.request().url().host(), call.request().url().encodedPath());
            }
            try {
                onFailure(call, new Throwable(e.getMessage() + ""));
            } catch (Exception e1) {
            }
        }
    }


    @Override
    public void onFailure(Call<T> call, Throwable t) {
        LogUtils.d("REST-API", "[onFailure] [" + m_strKey + "] error = " + t);
        try {
            Exception throwable = new Exception("error");
            onError(throwable);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getMessage(Throwable t) {
        String msg = null;
        if (t != null) {
            msg = t.getMessage();
        }

        return msg;
    }

    public abstract void onSuccess(T response);

    public abstract void onError(Throwable t);
}
